import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from "path";
import {files} from './files';


const fileTypes:Array<string>=['config.ts','tsx','less','ts'];

function wxCommandHander(type: string, e: vscode.Uri) {
	vscode.window.showInputBox({
		placeHolder: "enter title",
	})
	.then((title:string) => {

		if(!/^\w+$/.test(title)){
			vscode.window.showInformationMessage("文件名只能是数字、字母或_组合");
			return;
		}

		var dir = e.fsPath + "/" + title;

		if (fs.existsSync(dir)) {
			vscode.window.showInformationMessage("content already exist");
			return;
		}

		fs.mkdirSync(dir);

		console.log('%cextension.ts line:34 title', 'color: #007acc;', title);

		/**
		 * 文件路径
		 * dir + "/title.tsx";
		 */

		/**
		 * path.sep
		 * 提供平台特定的路径片段分隔符：
		 * Windows 上是 \
		 * POSIX 上是 /
		 */
		// const filename = String(dir).split(path.sep).pop();
		const filename = title;
		const { page, components } = files(`${filename}`);

		const stat = fs.statSync(e.fsPath);

		//获取pages上一级文件路径
		const dirParent = e.fsPath.replace(path.join('/pages'), '');

		console.log('%cextension.ts line:43 filename', 'color: #007acc;', filename);

		let models=fs.readFileSync(path.join(dirParent+'/models/index.ts'), 'utf8').split('\n');
		models=Array.from(new Set(models));
		models = models.filter(function (e) { return e.replace(/(\r\n|\n|\r)/gm, ""); });

		let modelsIndex = models.findIndex(function (value) { return value.indexOf('export')>=0;});

		let modelsText1="import "+filename+" from '../pages/"+filename+"/model'";
		let modelsText2:any=filename;

		models.splice(modelsIndex, 0, modelsText1);
		models.splice(modelsIndex+1, 0, "");
		models.splice(modelsIndex+1, 0, "");
		models.splice(modelsIndex+1, 0, "");

		models[models.length-2]=models[models.length-2]+',';
		models.splice(models.length-1,0,modelsText2);

		fs.writeFileSync(path.join(`${dirParent}/models/index.ts`), models.join('\n'));

		//配置文件
		let config: any = fs.readFileSync(path.join(`${dirParent}/app.config.ts`), 'utf-8').split('\n');
		//过滤换行符
		config = config.filter(function (e) { return e.replace(/(\r\n|\n|\r)/gm, "");  } );

		let pageIndex = config.findIndex(function (value) { return value.indexOf(']') >= 0; });
		config[pageIndex-1]=config[pageIndex-1]+',';

		const configText: string = "pages/" + filename + "/" + filename;
		config.splice(pageIndex, 0, "'" + configText + "'");

		fs.writeFileSync(path.join(`${dirParent}/app.config.ts`), config.join('\n'));



		if (stat.isDirectory()) {
			try {
				fileTypes.map(async(i: string) => {
					const data =  new Uint8Array(Buffer.from( type === 'page' ? page[i] : components[i]));
					if(i === 'ts'){
						fs.writeFileSync(path.join(`${dir}/model.${i}`), data);
					}
					else{
						fs.writeFileSync(path.join(`${dir}/${filename}.${i}`), data);
					}

				});

				vscode.window.showInformationMessage(`create ${type} success!`);
			} catch (error) {
				vscode.window.showErrorMessage('create page files failed');
			}
		} else {
			vscode.window.showErrorMessage('please choose a folder');
		}

	});
}
export function activate(context: vscode.ExtensionContext) {

	console.log('Congratulations, your extension "create-taro-page" is now active!');

	let disposable = vscode.commands.registerCommand('create-taro-page.createTaroPage', async(e:vscode.Uri) => {
		wxCommandHander('page',e);

	});

	context.subscriptions.push(disposable);

	vscode.commands.registerCommand('create-taro-page.createTaroComponents', async(e:vscode.Uri) => {
		wxCommandHander('components',e);
	});

	context.subscriptions.push(disposable);


}

export function deactivate() {}
